package main.java.com.lee.practise;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/3/3
 */
public class NLockCASAdd {
    int sum;
    private static Unsafe unsafe;
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        Class klass = Unsafe.class;
        Field field = klass.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        unsafe = (Unsafe) field.get(null);
        NLockCASAdd nLockCASAdd = new NLockCASAdd();
        nLockCASAdd.add();

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        IntStream.rangeClosed(1, 10).forEach(i->{
            executorService.submit(()-> {
                try {
                    nLockCASAdd.add();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            });
        });

        executorService.shutdown();
        while (!executorService.isTerminated()) {

        }
        System.out.println(nLockCASAdd.sum);

    }

    public void add() throws NoSuchFieldException {
        for (int i = 1; i < 10; i++) {
            do {

            } while (!unsafe.compareAndSwapInt(this, unsafe.objectFieldOffset(NLockCASAdd.class.getDeclaredField("sum")), sum, sum + 1));
        }

    }
}



